<?php

namespace app\api\controller;

use think\admin\Controller;

use think\Request;
/**
 * Class Goods
 * @package app\api\controller
 */
class Goods extends Controller
{
    private $default_type = 'json';
    protected $middleware = ['check'];
    public function __construct(Request $request){
        $this->request = $request;
    }
   /**
     * GET
     * 商品列表 - 搜索进
     * @return  true
     */
    public function lists(){
        if($this->request->debug != 1){
            $search = input('search','','trim');                //检索内容
            $page   = input('page',1,'trim,intval');            //页码
            $size   = input('size',10,'trim,intval');           //每页显示数量
            $sort_index = input('sort_index',0,'trim,intval');  //0 综合  1  销量  2  价格  3 上新
            $productList = [];
            $goodsModel = new \app\api\model\ShopGoods();
//            if($sort_index == 2){
//                $sort_by= input('sort_by',0,'trim,intval');         //0 升序   1 降序
//            }else{
//                $sort_by= input('sort_by',1,'trim,intval');         //0 升序   1 降序
//            }
//            $order = [];
//            if($sort_by == 0){
//                $sort_type = 'asc';
//            }else{
//                $sort_type = 'desc';
//            }
//            if($sort_index == 1){
//                $order['slogan'] = $sort_type;
//            }elseif ($sort_index == 2){
//                $order['price_selling'] = $sort_type;
//            }else{
//                $order['update_at'] = $sort_type;
//            }
            $order['sort'] = 'asc';
            $order['update_at'] = 'desc';
            $order['state_hot'] = 'desc';
            $total = 0;
            $productList = [];
            $where = [];
            $where[] = ['status','=',1];
            if(empty($search) === FALSE){
                $search = urldecode($search);
                $where[] = ['name|remark','like',"%".$search."%"];
                $tokeninfo = $this->request->tokeninfo;
                if(empty($tokeninfo) === FALSE){
                    \Common::saveSearch($search,$tokeninfo['id']);
                }
            }else{
                return \Tools::returnMsg(false,array(
                    'code'      => '100012',
                    'message'   =>'请输入检索内容'
                ),$this->default_type);
            }
             $total = $goodsModel->where($where)->count();
                $productList = $goodsModel->where($where)
                    ->order($order)
                    ->field('name,smail_cover as img,price_selling,id as goods_id,state_hot,stock_sales,stock_virtual,stock_sales+stock_virtual as slogan,remark,price_market')
                    ->limit(($page-1)*$size,$size)
                    ->select()->toArray();
                if(empty($productList)){
                    $productList = [];
                }else{
                    $rate = 1;
                    $can_show_newActiviy = sysconf('base.can_show_newActiviy');
                    foreach ($productList as &$pv){
                        $pv['price_market'] = sprintf("%.2f",$pv['price_market'] * $rate/100);
                        if($can_show_newActiviy == 1){
                            $rate = sysconf("base.newopenActivity_rate");
                            $pv['price'] = '￥'.sprintf("%.2f",$pv['price_selling'] * $rate/100);
                            $pv['price_selling'] = sprintf("%.2f",$pv['price_selling'] * $rate/100);
                        }else{
                            $pv['price'] = '￥'.sprintf("%.2f",$pv['price_selling']/100);
                            $pv['price_selling'] = sprintf("%.2f",$pv['price_selling']/100);
                        }
                    }
                }
        }
        return \Tools::returnMsg(true,array(
            'total' => $total,
            'productList' =>$productList
        ),$this->default_type);
    }

    /**
     * GET
     * 品牌商品列表
     * @return void
     */
    public function brandLists(){
        if($this->request->debug != 1){
            $brand_id = input('brand_id','','trim,intval');
            $page = input('page',1);
            $size = input('size',10);
            $sort_index = input('sort_index',0,'trim,intval');  //0 综合  1  销量  2  价格  3 上新

//            if($sort_index == 2){
//                $sort_by= input('sort_by',0,'trim,intval');         //0 升序   1 降序
//            }else{
//                $sort_by= input('sort_by',1,'trim,intval');         //0 升序   1 降序
//            }
//            $order = [];
//            if($sort_by == 0){
//                $sort_type = 'asc';
//            }else{
//                $sort_type = 'desc';
//            }
//            if($sort_index == 1){
//                $order['slogan'] = $sort_type;
//            }elseif ($sort_index == 2){
//                $order['price_selling'] = $sort_type;
//            }else{
//                $order['update_at'] = $sort_type;
//            }
             $order['sort'] = 'asc';
            $order['update_at'] = 'desc';
            $order['state_hot'] = 'desc';
            if(empty($brand_id)) return \Tools::returnMsg(false,array(
                    'code'  => '10003',
                    'message'=>'必传参数丢失'
                ),$this->default_type);
            $brandModel = new \app\api\model\ShopGoodsBrand();
            $brandinfo = $brandModel->getOne(array(
                'id'    => $brand_id,
                'status'=> 1
            ),'name as title,cover,id,remark');
            if(empty($brandinfo)) return \Tools::returnMsg(false,array(
                    'code'  => '10004',
                    'message'=>'参数有误'
                ),$this->default_type);
            $res = \Common::getBrandGoods($brand_id,$page,$size,$order);
            $total = $res[0];
            $productList = $res[1];
        }
        return \Tools::returnMsg(true,array(
                'brandInfo'     => $brandinfo,
                'total'         => $total,
                'productList'   => $productList
            ),$this->default_type);
    }
    /**
     * GET
     * 商品详情
     * @return  true
     */
    public function info(){
        if($this->request->debug != 1){
            $id = input('good_id','','trim,intval');//商品id
            if(empty($id)) return \Tools::returnMsg(false,array(
                    'code'  => '10003',
                    'message'=>'必传参数丢失'
                ),$this->default_type);
            $goodsModel = new \app\api\model\ShopGoods();
            $Show_img = [];
            $goodsInfo = $goodsModel->getOne(array(
                'id'    => $id
            ),'id,name,code,cover,price_selling as price,price_market,stock_total,stock_sales,stock_virtual,remark,content,slider,state_hot,service,can_drawback,type,remark,vedio');
            if(empty($goodsInfo) === FALSE){
                //轮播图
                $swiperList = [];
                if(empty($goodsInfo['slider']) === FALSE){
                    $imgList = explode('|',$goodsInfo['slider']);
                    if(empty($imgList) === FALSE){
                        foreach($imgList as $sk=>$sv){
                            $swiperList[] = array(
                                'id' => $sk,
                                'img' => $sv
                            );
                        }
                    }
                }
                //获取规格图片 加进轮播图中
                $Show_img[] = array(
                    'key'   => 0,
                    'img'   => $goodsInfo['cover']
                );
                unset($goodsInfo['slider']);
                //商品详情
                if(empty($goodsInfo['stock_virtual'])) $goodsInfo['stock_virtual'] = 0;
                if(empty($goodsInfo['stock_sales'])) $goodsInfo['stock_sales'] = 0;
                $rate = 1;
                $can_show_newActiviy = sysconf('base.can_show_newActiviy');
                if($can_show_newActiviy == 1){
                    $rate = sysconf("base.newopenActivity_rate");
                }
                $min_price = sprintf("%.2f",$goodsInfo['price'] * $rate/100);
                $max_price = sprintf("%.2f",$goodsInfo['price'] * $rate/100);
                $goodsInfo['number'] = $goodsInfo['stock_sales'] + $goodsInfo['stock_virtual'];
                $goodsInfo['price'] = '￥'.sprintf("%.2f",$goodsInfo['price'] * $rate/100);
                $goodsInfo['price_market'] = '￥'.sprintf("%.2f",$goodsInfo['price_market']/100);
                $goodsInfo['service'] = empty($goodsInfo['service']) ? '' : json_decode($goodsInfo['service'],true);
                $spec = [];
                $detailModel = new \app\api\model\ShopGoodsItem();
                $detailList = $detailModel->getLists(array(
                    'goods_code'    => $goodsInfo['code'],
                    'status'        => 1
                ),'id,name,goods_sku,cover as img,goods_spec,stock_sales,stock_total,price_selling as price,
                price_market,number_virtual','goods_sku',array(
                    'sort' => 'asc'
                ));

                if(empty($detailList) === FALSE){
                    foreach($detailList as &$dv){
                        if(empty($dv['stock_sales'])) $dv['stock_sales'] = 0;
                        if(empty($dv['number_virtual'])) $dv['number_virtual'] = 0;
                        if(sprintf("%.2f",$dv['price']/100) > $max_price){
                            $max_price = sprintf("%.2f",$dv['price'] * $rate/100);
                        }
                        $dv['stock_sales'] = $dv['stock_sales'] + $dv['number_virtual'];
                         $dv['price'] = '￥'.sprintf("%.2f",$dv['price'] * $rate/100);
                        $dv['price_market'] = '￥'.sprintf("%.2f",$dv['price_market']/100);
                        $swiperList[] = array(
                            'id' => count($swiperList),
                            'img' => $dv['img']
                        );
                        $Show_img[] = array(
                            'key'   => count($swiperList)-1,
                            'img'   => $dv['img']
                        );
                    }
                }
                if($max_price == $min_price){
                    $goodsInfo['price'] = '￥' . $min_price;
                }else {
                    $goodsInfo['price'] = '￥' . $min_price . '~' . $max_price;
                }
                $goodsInfo['spec'] = $detailList;
                //评论  收藏
                $goods['comment'] = [];
                $isKeep = 0;
                $descriptionStr = $goodsInfo['content'];
                //显示活动图
                $can_show_newActiviy = sysconf('base.can_show_newActiviy');
                //显示包邮范围
                $has_postage_paylimit = sysconf('base.has_postage_paylimit');
                $can_show_postage_paylimit = 0;
                if($has_postage_paylimit > 0){
                    $can_show_postage_paylimit = 1;
                }
                $result = array(
                    'swiperList'    => $swiperList,
                    'goodsDetail'   => $goodsInfo,
                    'isKeep'        => $isKeep,
                    'show_img'        => $Show_img,
                    'can_show_newActiviy'=>$can_show_newActiviy,
                    'descriptionStr'=> $descriptionStr,
                    'show_postage_paylimit'=>$can_show_postage_paylimit,
                    'has_postage_paylimit'=>$has_postage_paylimit
                );
            }else{
                return \Tools::returnMsg(false,array(
                    'code'  => '10004',
                    'message'=>'参数有误'
                ),$this->default_type);
            }
        }
        return \Tools::returnMsg(true, $result, $this->default_type);
    }

    /**
     * 为你推荐
     * @return void
     */
    public function recommended(){
        $id = input('good_id','','trim,intval');//商品id
        if(empty($id)) return \Tools::returnMsg(false,array(
            'code'  => '10003',
            'message'=>'必传参数丢失'
        ),$this->default_type);
        $goodsModel = new \app\api\model\ShopGoods();
        $Show_img = [];
        $goodsInfo = $goodsModel->getOne(array(
            'id'    => $id
        ),'id,cateids');
        $goods = [];
        $resGoods = [];
        if(empty($goodsInfo) === FALSE){
            $cateids_str = trim($goodsInfo['cateids'],',');
            $cateids_arr = explode(',',$cateids_str);
            $rate = 1;
            $can_show_newActiviy = sysconf('base.can_show_newActiviy');
            if($can_show_newActiviy == 1){
                $rate = sysconf("base.newopenActivity_rate");
            }
            foreach($cateids_arr as &$v){
                $order = ['price_selling'=>'asc'];
                $productList = $goodsModel->where([
                    ['cateids|remark','like',"%".$v."%"],
                    ['status','=',1]
                ])->order($order)
                    ->field('name,smail_cover as img,price_selling,id as goods_id,state_hot,stock_sales,stock_virtual,stock_sales+stock_virtual as slogan,remark,price_market')
                    ->select()->toArray();
                if(empty($productList) === FALSE){
                    foreach ($productList as &$pv){
                        $pv['price_market'] = sprintf("%.2f",$pv['price_market']/100);
                        $pv['price_selling'] = sprintf("%.2f",$pv['price_selling']*$rate/100);
                        $pv['price'] = sprintf("%.2f",$pv['price_selling']*$rate/100);
                        $goods[] = $pv;
                    }
                }
            }
            $recommond_num = sysconf('base.recommond_num');
            if(empty($goods) === FALSE){
                shuffle($goods);
                foreach($goods as $gk=>$gv){
                    if($gk < $recommond_num){
                        $resGoods[] = $gv;
                    }
                }
            }
        }
        return \Tools::returnMsg(true,array(
                'goods'     => $resGoods
            ),$this->default_type);
    }
    /**
     * GET
     * 商品分类
     * @return array|string
     */
    public function category(){
        if($this->request->debug != 1){
            $result = [];
            //列表
            $categoryModel = new \app\api\model\ShopGoodsCate();
            $lists = $categoryModel->getOneValue(array(
                'pid'   => 0,
                'status'=> 1
            ),'id');
            if(empty($lists) === FALSE){
                $result = $categoryModel->whereInList(array(
                    'status'=> 1
                ),'pid',implode(',',$lists),'id,name as title,cover as img,remark,type',array(
                    'sort'          => 'asc',
                    'is_homeshow'   =>'desc',
                    'create_at'    =>'desc'
                ));
//                if(empty($result) === FALSE){
//                    foreach($result as &$sv){
//                        if($sv['type'] == 0 || $sv['type'] == 1) {
//                            //图书或文具
//                            $sv['productList'] = [];
//                        }elseif ($sv['type'] == 2){
//                            //录播课
//                            $sv['productList'] = [];
//                        }else{
//                            //研学活动
//                            $sv['productList'] = [];
//                        }
//                    }
//                }
            }
            //图书列表中嵌套分类
            //文具展示列表
            //研学和录播课展示列表
        }
        return \Tools::returnMsg(true,$result,$this->default_type);
    }

    /**
     * 根据分类id活动对应商品
     * @return array|string
     */
    public function getcategorygoods(){
        $category_id = input('id',0,'trim,intval');
        $page = input('page',1,'trim,intval');      //当前页码
        $size = input('size',10,'trim,intval');     //每页展示数量
        if($category_id == 0){
            return  \Tools::returnMsg(false,array(
                'code'      => '90003',
                'message'   => '参数有误'
            ));
        }
        $cateRelaModel = new \app\api\model\ShopGoodsCateRela();
//        if($category_id == 25) {
//            $goodsModel = new \app\api\model\ShopGoods();
//            $where = array(
//                'status' => 1
//            );
//            $total = $goodsModel->checkNum($where);
//        }else{
            $total = $cateRelaModel->checkNum(array(
                'cate_id'   =>$category_id
            ));
//        }
        $productList = \Common::getCategoryGoods($category_id,0,$page,$size);
        return \Tools::returnMsg(true,array(
            'total' => $total,
            'lists' => empty($productList) ? [] : $productList['goodsList']
        ),$this->default_type);
    }
}
